using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharaMove : MonoBehaviour
{
    public float jumpHeight;
    public float moveSpeed;

    public Transform groundDetector1;
    public Transform groundDetector2;
    public LayerMask groundLayer;
    public float groundDetectDis;

    private Rigidbody2D rb;
    private Collider circleCollider;

    private bool onGround = false;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        circleCollider = GetComponent<Collider>();
    }

    // Update is called once per frame
    void Update()
    {
        PhysicsDetect();

        if(Input.GetButton("Jump"))
        {
            if(onGround && rb.velocityY <= 0)
            {
                //Debug.Log("Jump " + rb.velocityY);
                rb.velocity = new Vector2(rb.velocity.x, Mathf.Sqrt(-Physics2D.gravity.y * 2 * jumpHeight));

            }
        }

        transform.position += new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0, 0);
    }

    private void PhysicsDetect()
    {
        RaycastHit2D hit1 = Physics2D.Raycast(groundDetector1.position, Vector2.down, groundDetectDis, groundLayer);
        RaycastHit2D hit2 = Physics2D.Raycast(groundDetector2.position, Vector2.down, groundDetectDis, groundLayer);

        if(hit1 || hit2)
        {
            onGround = true;
        }
        else
        {
            onGround = false;
        }
        //Debug.Log(onGround);
    }
}
